package com.aerospace.example.helloworld;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName HelloServer
 * @Description
 * @Author yuhang11
 * @Date 2021/7/12 4:42 下午
 * @Version 1.0
 */
@Slf4j
public class HelloServer {
    private final int port;
    private final Server server;

    public HelloServer(int port) {
        this.port = port;
        server = ServerBuilder.forPort(port).build();
    }

    public static void main(String[] args) {
        try{
            HelloServer server = new HelloServer(50051);
            server.start();
            //server不自动关闭
            server.blockUntilShutDown();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void start() throws Exception {
        server.start();
        log.info("Hello Server started, listening on "+ port);
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @SneakyThrows
            @Override
            public void run() {
                server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
            }
        });
    }

    private void blockUntilShutDown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }
}
